<?php
namespace app\index\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
 use think\facade\View; 
class User extends Base
{
    public function initialize() {
    //  // 判定用户是否登录
    $login =session('userAccount');  
    $uid=$login['id'];
    if(!$login) {
        header('Location: /index/login');
    //   return $this->redirect('/index/login');
    }else {
 
   
      
      View::assign('loginsf',$login['username']);   // code...
      
      
    }
   
   
 
    


  }
    public function index()
    {
    $login =session('userAccount'); 
    $uid=$login['id'];
    if(!$login) {
        header('Location: /index/login');
    //   return $this->redirect('/index/login');
    }else {
        
        //会员判断开始
      $userdata=  Db::name('users')->where('id',$login['id'])->find();
      $userorderData=Db::name('order')->where('uid',$uid)->where('cate','3')->where('status','>','0')->max('paytime');
      $userorderData1=Db::name('order')->where('uid',$uid)->where('cate','3')->where('status','>','0')->where('paytime',$userorderData)->find();
      $over=$userorderData1['type'];
      $uservipover=$userdata['overtime'];
     if($userorderData != NULL && $userdata['viptime']!=$userorderData){   //判断是否有新订单，并且未执行
   
        if($userdata['viptime'] != NULL){
             
           if($over==1){
           $overtime=$userdata['overtime']+2678400; 
           }elseif($over==2){
           $overtime=$userdata['overtime']+32140800;  
           }else{
           $overtime=$userdata['overtime']+3181939200;
           }
         $res1=Db::name('users')->where('id', $uid)->update(['vip' => $over,'viptime' => $userorderData,'overtime' =>$overtime]);   
        }else{
           
           if($over==1){
           $overtime=time()+2678400; 
           }elseif($over==2){
           $overtime=time()+32140800;  
           }else{
           $overtime=time()+3181939200;
                }
           $res1=Db::name('users')->where('id', $uid)->update(['vip' => $over,'viptime' => $userorderData,'overtime' =>$overtime]); 
             }
      
        if($userdata['overtime']<time()){
          $res1=Db::name('users')->where('id', $uid)->update(['vip' => '0','viptime' => '','overtime' =>'']); 
          } 
         
    
          }       
     
    
  
     
      
        //会员判断结束
        
    $userdata=  Db::name('users')->where('id',$login['id'])->find();
      $buy=Db::name('order')->alias('a')->
            field('b.id,b.title,b.description')->
            join('website b','a.webid=b.id')->
            where('a.uid',$login['id'])->where('a.status',">",'0')->where('a.cate','1')->
             select();
      $order=Db::name('order')->alias('a')->where('a.uid',$login['id'])->where('a.status',">",'0')->select();      
        return view('',[
          'userdata'=>$userdata,
          'buy'=>$buy,
          'order'=>$order,
          'uservipover'=>$uservipover,
          
        ]);
    }
    }
  public function download()
    {
     $login =session('userAccount');     
    if(!$login) {
        header('Location: /index/login');
    //   return $this->redirect('/index/login');
    }else {
    
      
    $id=input('post.id');
 
    $userdata=  Db::name('users')->where('id',$login['id'])->find();
    $orderdata= Db::name('order')->where('uid',$login['id'])->where('status','>=',1)->where('webid',$id)->find();
   
    if($orderdata == NULL){
    Header("Location:/index/index/product?id=$id");
    
    }else{
       
         $download=  Db::name('website')->where('id',$id)->find(); 
        return view('',[
          'userdata'=>$userdata,
          'download'=>$download,
          'jiaocheng'=>$download['jiaochengid'],
          'orderdata'=>$orderdata,
          'loginsf'=>$login['username'],
        ]);
      
    }
    }  
      
    }
    public function update($file_url) {
     
        $filename = basename($file_url); 
        $dir = App::getRootPath(). "runtime/update/";
       
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $path = file_exists($dir.$filename)?$dir.$filename:$this->download_file($file_url,$dir,$filename);
        if (!file_exists($dir.$filename)) {
            return json(["msg" => '100！', "code" => 100]);
        }

        if(!class_exists("\ZipArchive")) return json(['code' => 100, 'msg' => '100！']);
 
   
        $zip = new \ZipArchive();
 
    
        if ($zip->open($path) === true) {
        
            $toPath = App::getRootPath();
            try {
         
                $zip->extractTo($toPath);
          
                unset($zip);
             
                unlink($path);
            } catch (\Exception $e) {
                return json(["msg" => "100", "code" => 100]);
            }
 
          
            if(file_exists(App::getRootPath() . "/sql.php")){
           
                include App::getRootPath() . "/sql.php";
                chmod(App::getRootPath() . "/sql.php",0777);
                unlink(App::getRootPath() . "/sql.php");
            }
         
            return json(["msg" => "200！", "code" => 200]);
        } else {
          
            unlink($path);
            return json(["msg" => "100", "code" => 100]);
        }
    }
  
    public function download_file($url, $dir, $filename = '') {
        if (empty($url)) {
            return false;
        }
        $ext = strrchr($url, '.');
 
        $dir = realpath($dir);
        //目录+文件
        $filename = (empty($filename) ? '/' . time() . '' . $ext : '/' . $filename);
        $filename = $dir . $filename;
        //开始捕捉
        ob_start();
 
        try {
            readfile($url);
        } catch (\Exception $e) {
            return json(["msg" => "文件下载失败，请联系开发人员！", 'code' => 100]);
        }
 
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp2 = fopen($filename, "a");
        fwrite($fp2, $img);
        fclose($fp2);
        return $filename;
    }
  public function vip(){
 
 
        return view('',[
    
        ]);
    }
     public function token(){
 
   $login =session('userAccount');     
    if(!$login) {
        header('Location: /index/login');
    //   return $this->redirect('/index/login');
    }else {
    
      
    $id=input('post.id');
 
    $userdata=  Db::name('users')->where('id',$login['id'])->find();
 
    }
        return view('',[
   'userdata'=>$userdata,
        ]);
    }
public function recharge(){
 
 
        return view('',[
    
        ]);
    }
public function balancepay(){  //余额支付
    $login =session('userAccount');     
    if(!$login) {
        header('Location: /index/login');
    }else {
     $get=input('post.');
     $order=$get['orerres'];
     $uid=$login['id'];
     $userData=Db::name('users')->where('id',$uid)->find();
     $amount=$userData['amount'];
     $orderData=Db::name('order')->where('id',$order)->find();
     $orderamount=$orderData['amount'];
     $cha=$amount-$orderamount;
     $zhifudanhao=$orderData['payorers'];
     if($cha>=0){
          $res=Db::name('users')->where('id', $uid)->update(['amount' => $cha]);
         $res1=Db::name('order')->where('id', $order)->update(['status' => '3','paytime' => time(),'payorers' =>$zhifudanhao]);
         return alert('购买成功，将跳转至会员中心','/index/user',6,3);  
     }else{
         return alert('余额不足，请充值！跳转回会员中心页面','/index/user',5,3);  
     }
    }
       
    }


    public function order(){
 
 
        return view('',[
    
        ]);
    }


    public function buy(){
   $login =session('userAccount');     
    if(!$login) {
        header('Location: /index/login');
    //   return $this->redirect('/index/login');
    }else {   
 
$get=input('post.');
$cate=$get['paycate'];
$uid=$login['id'];
$Num2 = rand(10000,99999);
$orderdata=date('YmdHis').$Num2;
$time=date('Y-m-d H:i:s');
$type=$get['type'];
$wid=$get['id'];
if($cate == 1){   //源码购买

    $archivesData=Db::name('website')->where('id',$wid)->find();
    $userorderData=Db::name('order')->where('uid',$uid)->where('webid',$wid)->where('status','>','0')->max('type');
    $data['webid']=$wid;
    $data['name']=$archivesData['title'];
    $data['type']=$type;
     if($userorderData==0){
       if($type==1){
        $jiage=$archivesData['jiage'];
        $fangshi='单源码';
 
       }elseif ($type==2) {
        $jiage=$archivesData['ajjiage']; 
        $fangshi='源码+安装';
       }elseif($type==3){
        $jiage=$archivesData['ytljiage'];  
        $fangshi='一条龙服务(直接成品交付)';
       }else{
        $jiage=$archivesData['jiage'];
        $fangshi='单源码';  
            }  
    }elseif($userorderData==1){
       if ($type==2) {
       $jiage=$archivesData['ajjiage']-$archivesData['jiage']; 
       $fangshi='已购买源码。补差价购买安装服务';
       }elseif($type==3){
       $jiage=$archivesData['ytljiage']-$archivesData['jiage'];  
       $fangshi='已购买源码。补差价升级一条龙服务(直接成品交付)';
       }else{
       $jiage=$archivesData['jiage'];
       $fangshi='单源码';  
            }
    }elseif($userorderData==2){   
 
       $jiage=$archivesData['ytljiage']-$archivesData['ajjiage'];  
       $fangshi='已购买安装服务。补差价升级一条龙服务(直接成品交付)'; 
    }else{
        
    }
}elseif($cate == 2){//余额充值
   $jiage=$get['amount'];
   $fangshi="账户余额充值";
   $archivesData['title']="账户余额充值";
   $data['name']="账户余额充值";
    
}elseif($cate == 3){//开通会员
   $jiage=$get['amount'];
   $fangshi="开通会员";  
   $archivesData['title']="开通会员";
   $data['name']="开通会员";
   $data['type']=$get['vip'];
   
}else{
        
    }
$timenow=time();
$data['uid']=$uid;
$data['amount']=$jiage;
$data['time']=$timenow;
$data['status']='0';
$data['orders']=$orderdata;
$data['cate']=$cate;

    $orerres=Db::name('order')->insertGetId($data);
    $deletetime= time()-600;
    $delete = Db::name('order')->where('status','0')->where('time','<',$deletetime)->delete();
    $orderressData=Db::name('order')->where('id',$orerres)->find();

        return view('',[
        'archivesData'=>$archivesData ,
        'orderressData'=>$orderressData ,
        'fangshi'=>$fangshi ,
        'loginsf'=>$login['username'],
        'cate'=>$cate,
        'orerres'=>$orerres,
        ]);
    }
    }
  public function edit(){
     $login =session('userAccount');     
    if(!$login) {
        header('Location: /index/login');
    //   return $this->redirect('/index/login');
    }else {   
     $uid=$login['id'];
     $userData=Db::name('users')->where('id',$uid)->find();
     if(request()->isPost()){

         $data = input('post.');
         
         if(!empty($data['email'])){
           $res['email']=$data['email'];  
         }else{
            $res['email']=$userData['email'];   
         }
          if(!empty($data['password'])){
            $res['password']=$this->password_salt($data['password']);  
         }else{
            $res['password']=$userData['password'];   
         }
        
         $userData=Db::name('users')->where('id',$uid)->update($res);
         if($userData) {
           return alert('修改成功！跳转会员中心页面','/index/user',6,3); 
         }else{
           return alert('修改失败！跳转会员中心页面','/index/user',5,3);   
         }
        } 
   
     
            
        return view('',[
          'userData'=>$userData, 
           'loginsf'=>$login['username'],
        ]);
    }
  }
    public function contact(){
        $id=7;
        $categoryData=Db::name('category')->find($id);
        return view('',[
            'categoryData'=>$categoryData,
            'menu_id'=>7
        ]);
    }

    public function article(){
        $id=input('id');

       $archivesData=Db::name('archives')->find($id);
       $categoryData=Db::name('category')->find($archivesData['cate_id']);

        return view('',[
            'categoryData'=>$categoryData,
            'archivesData'=>$archivesData,
            'menu_id'=>$id
        ]);
    }
  public function outlogin() {

      // 清除session
      session(null);

      // 跳出
      return redirect('/index/index');

  }
  
}
